package com.bw.controller;

import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 第三方账号的绑定 需要先进行普通登录
 */
@Controller
public class GiteeBindController {

    @Autowired
    UserMapper userMapper;

//    @RequestMapping("callbackCode.do")
    public String callbackCode(String code, HttpServletRequest request,HttpServletResponse response){

        System.out.println("接收到的临时授权码 " + code);

        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);

        System.out.println("获取到的用户信息 " + userInfoByToken.toJSONString());

        // 从gitee账号中 解析出三个字段

        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        Integer giteeId = userInfoByToken.getInteger("id");

         // 合并两个账号
        // 获取当前登录用户  从request中解析出当前登录用户 Tom
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        userFromRequest.setNickName(nickName);
        userFromRequest.setGiteeId(giteeId);
        userFromRequest.setAvatarUrl(avatarUrl);

        userMapper.updateUser(userFromRequest);

        // 因为用户信息发生改变了， 需要重新制作令牌，加密用户  得到token 把token放入cookie 返回给浏览器
        TokenUtils.responseTokenByCookie(userFromRequest,response,30);

        return "redirect:list.do";
    }
}
